package com.tf.six.config;

import com.tf.six.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private CustomUserDetailsService customUserDetailsService; // 你的 UserDetailsService

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 授权规则配置（Spring Security 6.x 新写法）
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/users/register", "/api/users/login",
                                "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**").permitAll()
                        .anyRequest().authenticated()
                )
                // 表单登录配置（链式调用优化）
                .formLogin(form -> form
                        .loginPage("/login.html") // 自定义登录页（按需替换实际路径）
                        .loginProcessingUrl("/api/users/login") // 登录提交的 URL
                        .defaultSuccessUrl("/api/users", true) // 登录成功跳转（按需调整）
                        .permitAll()
                )
                // HTTP Basic 认证（链式调用优化，若不需要可删除）
                .httpBasic(httpBasic -> httpBasic
                        .realmName("MyAppRealm") // 可选：配置 Realm
                        .authenticationEntryPoint((request, response, authException) -> {
                            response.sendError(401, "Unauthorized"); // 自定义未授权响应
                        })
                )
                // 关闭 CSRF（开发环境方便测试，生产建议开启并配置）
                .csrf(csrf -> csrf.disable());

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
        builder.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
        return builder.build();
    }
}